package com.example.exam.service.impl;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.exam.mapper.TExamPaperAnswerMapper;
import com.example.exam.mapper.TExamPaperQuestionCustomerAnswerMapper;
import com.example.exam.pojo.DTO.ExamPaperAnswerDTO.*;
import com.example.exam.pojo.Enum.ExamPaperAnswerStatusEnum;
import com.example.exam.pojo.Exception.ServiceException;
import com.example.exam.pojo.entity.TExamPaperAnswer;
import com.example.exam.pojo.entity.TExamPaperQuestionCustomerAnswer;
import com.example.exam.pojo.vo.ExamPaperAnswerVO.AnswerItemCorrectVO;
import com.example.exam.pojo.vo.ExamPaperVO.ExamPaperEditStandardVO;
import com.example.exam.service.ICustomerAnswerService;
import com.example.exam.service.IExamPaperAnswerService;
import com.example.exam.tools.BaseApiController;
import com.example.exam.tools.JsonPage;
import com.example.exam.tools.JsonUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Transactional
@Slf4j
@Service
public class ExamPaperAnswerImpl extends BaseApiController implements IExamPaperAnswerService {
    @Autowired
    private TExamPaperAnswerMapper examPaperAnswerMapper;
    @Autowired
    private ICustomerAnswerService customerAnswerService;
    @Autowired
    private TExamPaperQuestionCustomerAnswerMapper customerAnswerMapper;

    @Override
    public void export(HttpServletResponse response,PaperAnswerDTO paperAnswerDTO) throws IOException {
        log.debug("开始处理【导出】的业务");
        //1.查询要导出的试卷
        List<TExamPaperAnswer> list = examPaperAnswerMapper.examPaperAnswerFinished(paperAnswerDTO);
        System.out.println(list);
        //2.设置响应内容类型和响应头
        response.setContentType("application/vnd.ms-excel");
        //设置响应头，让浏览器弹出下载保存的对话框，并指定下载文件的名称
        String filename = "成绩单"+System.currentTimeMillis()+".xls";
        //文件名不能带有中文，所有需要对中文进行编码
        filename = URLEncoder.encode(filename,"utf-8");
        response.addHeader("Content-Disposition","attachment;filename="+filename);

        //3.获取Excel输出流和响应对象的输出流
        try(ExcelWriter writer = ExcelUtil.getWriter();
            ServletOutputStream out = response.getOutputStream()){

            //设置实体类属性与excel标题的映射关系
            writer.addHeaderAlias("id","id");
            writer.addHeaderAlias("paperName","试卷名称");
            writer.addHeaderAlias("studentName","用户名称");
            writer.addHeaderAlias("userScore","得分");
            writer.addHeaderAlias("doTime","耗时（min）");
            writer.addHeaderAlias("createTime","提交时间");

            //将查询出来的商品数据通过excel输出流写出到内存中的excel表格
            writer.write(list);
            //5.将内存中构建的excel表格通过响应对象的输出流写出到浏览器
            writer.flush(out);
            log.debug("已批改试卷导出完成！");
        }



    }

    @Override
    public Integer judge(List<AnswerItemCorrectVO> answerItemCorrectVOs) {
        log.debug("正在处理【批改试卷】的业务...");
        log.debug("answerItemCorrectVOs={}",answerItemCorrectVOs);
        Integer totalScore =0 ;
        Integer id = 0;
        for (AnswerItemCorrectVO item:answerItemCorrectVOs) {
            totalScore+= item.getCustomerScore();
            id=item.getId();
            customerAnswerMapper.updateScore2(item);
        }
        Integer examPaperAnswerId = customerAnswerMapper.selectExamPaperAnswerIdById(id);
        TExamPaperAnswer answer = new TExamPaperAnswer();
        answer.setId(examPaperAnswerId);
        answer.setUserScore(totalScore);
        answer.setStatus(1);
        examPaperAnswerMapper.update(answer);
        log.debug("totalScore="+totalScore);
        return totalScore;
    }


    @Override
    public JsonPage<TExamPaperAnswer> getExamPaperAnswerByPage(PaperAnswerDTO paperAnswerDTO) {
        log.debug("正在处理【分页查询未批改试卷列表】的业务...");
        PageHelper.startPage(paperAnswerDTO.getPageIndex(), paperAnswerDTO.getPageSize());
        List<TExamPaperAnswer> listByPage = examPaperAnswerMapper.findExamPaperAnswer(paperAnswerDTO);
        return JsonPage.restPage(new PageInfo<>(listByPage));
    }

    @Override
    public JsonPage<TExamPaperAnswer> getFinishedPaperAnswerByPage(PaperAnswerDTO paperAnswerDTO) {
        log.debug("正在处理【分页查询已批改试卷列表】的业务...");
        PageHelper.startPage(paperAnswerDTO.getPageIndex(), paperAnswerDTO.getPageSize());
        List<TExamPaperAnswer> listByPage = examPaperAnswerMapper.examPaperAnswerFinished(paperAnswerDTO);
        return JsonPage.restPage(new PageInfo<>(listByPage));
    }

    @Override
    public TExamPaperAnswer selectById(Integer id) {
        log.debug("正在处理【根据ID查询试卷答案】的业务...");
        TExamPaperAnswer tExamPaperAnswer = examPaperAnswerMapper.selectById(id);
        if(tExamPaperAnswer==null){
            String message = "ID为{}的试卷答案不存在！";
            log.warn("查询失败！{}",message);
            throw new ServiceException(404,message);
        }
        return tExamPaperAnswer;
    }

    @Override
    public ExamPaperSubmitDTO getPaperAnswerById(Integer id) {
        log.debug("正在处理【根据ID查询用户答案】的业务...");
        ExamPaperSubmitDTO examPaperSubmitDTO = new ExamPaperSubmitDTO();
        TExamPaperAnswer examPaperAnswer = examPaperAnswerMapper.selectById(id);
        examPaperSubmitDTO.setDoTime(examPaperAnswer.getDoTime());
        examPaperSubmitDTO.setId(examPaperAnswer.getId());
        examPaperSubmitDTO.setScore(examPaperAnswer.getPaperScore());
        List<TExamPaperQuestionCustomerAnswer> answers = customerAnswerService.listByPaperAnswerId(examPaperAnswer.getId());
        List<ExamPaperSubmitItemDTO> itemDTOs = answers.stream()
                .map(a -> customerAnswerService.getCustomerAnswer(a))
                .collect(Collectors.toList());
        examPaperSubmitDTO.setAnswerItems(itemDTOs);
        return examPaperSubmitDTO;

    }
}
